package com.sunday.aomicaichang.ui.widgets;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.ui.MallFoodDetailActivity;
import com.sunday.aomicaichang.ui.MallOrderConfirmActivity;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.order.OrderConfirm;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PopBuyMallWindow extends PopupWindow {


    @Bind(R.id.sub)
    ImageView sub;
    @Bind(R.id.show_num)
    EditText showNum;
    @Bind(R.id.add)
    ImageView add;
    @Bind(R.id.linearLayout)
    LinearLayout linearLayout;
    @Bind(R.id.btn_confirm)
    TextView btnConfirm;
    @Bind(R.id.popu_top_img)
    ImageView popuTopImg;
    @Bind(R.id.top)
    LinearLayout top;
    @Bind(R.id.product_price)
    TextView productPrice;
    @Bind(R.id.product_store_num)
    TextView productStoreNum;

    private Context mContext;
    private int buyType;//1:立即购买 2：加入购物车
    private int appWidth;
    private View windowView;
    private OnSelectListener onSelectListener;
    private long productId;
    private String proPrice,productImage;
    private int saleNum;
    private int villageId;
    private BigDecimal oldPrice;

    public PopBuyMallWindow(Context context, int buyType, String proImg, long productId, String price, int saleNum,BigDecimal oldPrice) {
        villageId= SharePerferenceUtils.getIns(mContext).getInt(com.sunday.aomicaichang.constValues.ConstValue.AREA,0);
        this.mContext = context;
        this.buyType = buyType;
        this.productImage=proImg;
        this.productId=productId;
        this.proPrice=price;
        this.saleNum=saleNum;
        this.oldPrice=oldPrice;
        appWidth = DeviceUtils.getDisplay(mContext).widthPixels;
        windowView = LayoutInflater.from(mContext).inflate(R.layout.layout_pop_buy_window, null);
        setContentView(windowView);
        ButterKnife.bind(this, windowView);
        this.setWidth(appWidth);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setOutsideTouchable(true);
        this.setFocusable(true);
        this.setOnDismissListener(new PoponDismissListener());
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setAnimationStyle(com.sunday.common.R.style.popuwindow);
        showNum.setEnabled(false);
        initView();
    }

    public void setBuyType(int buyType) {
        this.buyType = buyType;
    }



    private void initView(){
        if (!TextUtils.isEmpty(productImage)){
            Picasso.with(mContext)
                    .load(productImage)
                    .resize(150,150)
                    .error(R.mipmap.ic_product)
                    .into(popuTopImg);
        }
        productPrice.setText(proPrice+"积分");
//        productStoreNum.setText(String.format("销量%d",saleNum));

        productStoreNum.setText(String.format("￥%s", oldPrice.setScale(2, RoundingMode.HALF_UP)));
        productStoreNum.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    private int buyNum = 1;

    @OnClick({R.id.sub, R.id.add, R.id.btn_confirm})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.sub:
                if (buyNum == 1) {
                    return;
                }
                buyNum--;
                showNum.setText(String.valueOf(buyNum));
                break;
            case R.id.add:
                buyNum++;
                showNum.setText(String.valueOf(buyNum));
                break;
            case R.id.btn_confirm:
                submit();
                /*if (onSelectListener != null ) {
                    onSelectListener.onSelect(buyNum,buyType);
                }*/
                this.dismiss();
                break;
        }
    }


    //显示
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            backgroundAlpha(0.5f);
        } else {
            this.dismiss();
        }
    }

    public void setOnSelectListener(OnSelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
    }

    /**
     * 弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class PoponDismissListener implements OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
            dismiss();
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) mContext).getWindow().setAttributes(lp);
    }

    public interface OnSelectListener {
        void onSelect(int number, int buyType);
    }

    private void submit(){
        if (buyType== ConstValue.TYPE_ADDCART){
            //add cart
            addCart();
        }else {
            //buy now
            buyNow();
        }
    }

    private void addCart(){
        String nonce= MD5Utils.random();
        String[] str1=new String[]{"productIds","villageId","nums","nonce"};
        String[] str2=new String[]{String.valueOf(productId),String.valueOf(villageId),String.valueOf(buyNum),nonce};
        ((MallFoodDetailActivity)mContext).showLoadingDialog(0);
        Call<ResultDO>call= MemberClient.getApiAdapter().addCart(villageId,String.valueOf(productId),
                String.valueOf(buyNum),nonce, SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                ((MallFoodDetailActivity)mContext).dissMissDialog();
                if(response.body()==null){return;}
                if (response.body().getCode()==0){
                    Toasty.success(mContext,"成功加入购物车").show();
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ((MallFoodDetailActivity)mContext).dissMissDialog();
                Toasty.error(mContext,"网络连接错误").show();
            }
        });
    }

    private void buyNow(){
        String nonce= MD5Utils.random();
        String[] str1=new String[]{"productId","villageId","number","isUsedBalance","couponId","sendType","nonce"};
        String[] str2=new String[]{String.valueOf(productId),String.valueOf(villageId),String.valueOf(buyNum),"0","0","1",nonce};
        ((MallFoodDetailActivity)mContext).showLoadingDialog(0);
        Call<ResultDO<OrderConfirm>>call= ApiClient.getApiAdapter().countBuyNow(productId,buyNum,villageId,0,0,1,nonce, SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO<OrderConfirm>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderConfirm>> call, Response<ResultDO<OrderConfirm>> response) {
                ((MallFoodDetailActivity)mContext).dissMissDialog();
                if(response.body()==null){return;}
                if (response.body().getCode()==0){
                    Intent intent=new Intent(mContext, MallOrderConfirmActivity.class);
                    intent.putExtra("orderConfirm",response.body().getResult());
                    mContext.startActivity(intent);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<OrderConfirm>> call, Throwable t) {
                ((MallFoodDetailActivity)mContext).dissMissDialog();
                Toasty.error(mContext,"网络连接错误").show();
            }
        });
    }


}
